
async function workerManager(jsPath,callback){
	let res=await fetch(jsPath);
	let jsCode=await res.text();
	jsCode+=`
	;onmessage=async ev=>{
		let {id,name}=ev.data;
		if(name && self[name]){
			let res=await self[name]();
			let data={data:res,time:Date.now(),id};
			postMessage(data);
			data=null;
			ev=null;
		}
	}
	`;
	let blob=new Blob([jsCode],{type:"text/javascript"});
	let worker=new Worker(URL.createObjectURL(blob));
	let id=0;
	let cachePromise={};
	
	worker.onmessage=async ev=>{
		//json.parse性能不如字符串split，长数据应以字符串形式传送，接收时用split分隔数据
		let msg=ev.data;
		if(callback){
			callback(msg.data);
		}else if(cachePromise[msg.id]){
			cachePromise[msg.id].resolve(msg.data);
		}
		delete cachePromise[msg.id];
		ev=null;
	}
	
	function destroy(){
		worker.terminate();
		worker=null;
		cachePromise={};
	}
	
	function exec(name,data){
		if(!worker){
			console.log('worker不存在')
		}
		id++;
		worker.postMessage({id,name,data});
		cachePromise[id]=Promise.withResolvers();
		return cachePromise[id].promise;
	}
	
	return new Proxy({},{
		get(target,key){
			if(key=="destroy"){
				return destroy;
			}else if(key=="worker"){
				return worker;
			}else{
				if(key=='then'){
					return null;
				}
				if(callback)return null;
				return data=>exec(key,data);
			}
		}
	});	
}
export {workerManager};